package com.spit.fammo.ui.frg

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ThreadUtils
import com.google.gson.Gson
import com.spit.amoeba.base.BaseFragment
import com.spit.fammo.R
import com.spit.fammo.bean.db.AssetBean
import com.spit.fammo.databinding.FAssetSearchBinding
import com.spit.fammo.ext.showMessage
import com.spit.fammo.mar.eventViewModel
import com.spit.fammo.util.MusicUtils
import com.spit.fammo.viewmodel.AssetModel
import com.spit.fammo.viewmodel.RfidModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * @Author nike
 * @Date 2023/8/2 14:17
 * @Description
 */
class AssetSearchFrg: BaseFragment<AssetModel, FAssetSearchBinding>() {

    val rfidModel: RfidModel by activityViewModels()

    val mHandler = Handler(Looper.getMainLooper())

    override fun initView(savedInstanceState: Bundle?) {
        arguments?.let {
            var bean = Gson().fromJson(it.getString("bean") , AssetBean::class.java)
            mViewModel.epc.set(bean.epc)
        }
        MusicUtils.init(activity)
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                mViewModel.isOpen.set(false)
                rfidModel.isSearchOpen.value = null
                rfidModel.epcData.value = null
            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                MusicUtils.clear()
                mHandler.removeCallbacksAndMessages(null)
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        rfidModel.epcData.observe(viewLifecycleOwner, Observer {
            if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
                if (it == null || !mViewModel.epc.get().trim().equals(it.TagId))return@Observer
                var rssi = it.Rssi?.replace("-", "")!!.toDouble()

                mHandler.removeCallbacks(delayTask)
                ThreadUtils.runOnUiThread {
                    mDatabind.scSignal.setRssi(rssi.toInt())

                    var rssi = rssi.toInt()
                    when {
                        rssi in 1..35 -> {
                            MusicUtils.setPlayCount(3)
                            MusicUtils.setSpeechRate(2.0f)
                        }
                        rssi in 36..49 -> {
                            MusicUtils.setPlayCount(2)
                            MusicUtils.setSpeechRate(1.5f)
                        }
                        /*rssi in 50..59 -> {

                        }
                        rssi in 60..69 -> {

                        }
                        rssi > 70 -> {

                        }*/
                        else -> {
                            MusicUtils.setPlayCount(1)
                            MusicUtils.setSpeechRate(1.0f)
                        }
                    }
                    MusicUtils.play()
                    mHandler.postDelayed(delayTask, 2000)
                }
            }
        })

        eventViewModel.uploadAsset.observeInFragment(this, {
            mViewModel.epc.set(it.epc)
        })
    }

    // 定义一个延迟任务的 Runnable
    val delayTask = Runnable {
        mDatabind.scSignal.setRssi(0)
    }

    inner class ProxyClick() {

        fun start(){
            if (StringUtils.isEmpty(mViewModel.epc.get()) || mViewModel.epc.get().equals("null")){
                showMessage(message = getString(R.string.notag_found))
                return
            }
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                val configBean = mViewModel.configDao.findFirst()
                configBean.powerType = 1
                mViewModel.configDao.update(configBean)
                mViewModel.isOpen.set(!mViewModel.isOpen.get())
                rfidModel.isSearchOpen.postValue(if (mViewModel.isOpen.get()) mViewModel.epc.get() else null)
            }
        }
    }

}